package com.showcai.core.aspect;

import com.showcai.core.util.ResposeUtil;
import com.showcai.log.LogFactory;
import com.showcai.module.VisitLog;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.result.ResultObj;
import com.showcai.result.ReturnCode;
import com.showcai.service.VisitLogService;
import com.showcai.tools.json.JsonHandler;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by Baggio on 2018-2-1.
 */
@Component
@Aspect
public class ControllerAspct {
    protected Logger logger = LogFactory.getLogger(getClass());

@Autowired
VisitLogService visitLogService;

    @Pointcut("execution(* com.showcai.controller..*.*(..))")
    public void controllerAop(){}

    @Before("controllerAop()")
    public void beforeController(JoinPoint joinPoint){
        logger.info("===============Before=====================>>>>>>>>>>>>>>>>>>>>>>>");
        System.out.println("Spring AOP");
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        logger.warn(className + "的" + methodName + "执行了");
        VisitLog visitLog=new  VisitLog();
        visitLog.setClassName(className);
        visitLog.setMethodName(methodName);
        Object[] args = joinPoint.getArgs();
        StringBuilder log = new StringBuilder("入参为");
        StringBuilder parameters = new StringBuilder();
        for (Object arg : args) {
            parameters.append(arg+",");
            log.append(arg + " ");
        }
        visitLog.setParameters(parameters.toString());
        visitLog.setCreateTime(new Date());
        try {
            visitLogService.createVisitLog(visitLog);
        } catch (MyRunTimeExcption myRunTimeExcption) {
            myRunTimeExcption.printStackTrace();
        }catch (Exception excption) {
            excption.printStackTrace();
        }
        logger.warn(log.toString());




    }
    @After("controllerAop()")
    public void afterController(){

        System.out.println("Spring AOP");
        logger.info("===================After=================>>>>>>>>>>>>>>>>>>>>>>>");
    }
    @AfterThrowing(pointcut = "controllerAop()", throwing="e")
     public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        System.out.println("Spring AOP");
        logger.info("===================doAfterThrowing=================>>>>>>>>>>>>>>>>>>>>>>>");
        ResultObj resultObj=new ResultObj();
        //不需要再记录ServiceException，因为在service异常切面中已经记录过

        if(e instanceof MyRunTimeExcption){
            resultObj.setCode(((MyRunTimeExcption) e).getErroCode());
            resultObj.setMsg(e.getMessage());
        }
      else{
            resultObj.setCode(ReturnCode.SYSTEM_ERRO.getCode());
            resultObj.setMsg(ReturnCode.SYSTEM_ERRO.getMsg());
        }
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        ResposeUtil.writeContent(JsonHandler.objectToJson(resultObj),response);
    }


    }
